<template>
    <PageTemplate>
    <div class="cbp-plan-detail" slot="content">
        <div class="container container-top " >
            <el-form  label-width="150px"  :model="capaCity" ref="capaCity" >
                <el-collapse v-model="showCollapse2" accordion>
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('cm.baseinfo')}}</font>
                        </template>
                        <div class="div-form">
                            <el-row>
                                <!--主题-->
                                <el-col :span="12">
                                    <el-form-item  :label="$t('pur.process_folio')"  prop="folio">
                                        <el-input   size="small" class="form-input" v-model="capaCity.folio" :disabled="true" placeholder="提交后自动生成"></el-input>
                                    </el-form-item>
                                </el-col>
                                <!--流程名称-->
                                <el-col :span="12">
                                    <el-form-item :label="$t('pur.process_procChName')">
                                        <el-input   size="small" class="form-input" v-model="flow_access.procChName" :disabled="true"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                <el-collapse v-model="showCollapse" accordion>
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >计划信息</font>
                        </template>
                        <div class="div-form">
                            <el-row v-if="type =='add'|| type =='edit' || type =='close'">
                              <el-col :span="12">
                                    <el-form-item  label="操作类型" required>{{operationMap[type]}}</el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                               <el-col :span="12" v-if="type != 'add'">
                                    <el-form-item  label="年度计划"  prop="planName" :rules="rules">
                                        <!-- <el-select v-if="edit "  class="form-input" v-model="capaCity.planName" size="small" :placeholder="$t('fe.pselect')" >
                                            <el-option label="能建项目1-2020" value="2020"></el-option>
                                            <el-option label="能建项目1-2019" value="2019"></el-option>
                                            <el-option label="能建项目1-2018" value="2018"></el-option>
                                        </el-select> -->
                                        <span>{{capaCity.planName}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="能力建设名称" prop="projectName" :rules="rules">
                                        <el-input v-if="edit"  class="form-input" v-model="capaCity.projectName" size="small" placeholder="50个汉字以内" ></el-input>
                                        <span v-else>{{capaCity.projectName}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item  label="立项年度"  prop="year" :rules="rules">
                                        <el-select
                                            v-if="edit"
                                            class="form-input"
                                            v-model="capaCity.year"
                                            size="small"
                                            :placeholder="$t('fe.pselect')" >
                                            <el-option
                                              v-for="item in nextThreeYear"
                                              :key="item"
                                              :label="item"
                                              :value="item">
                                            </el-option>
                                        </el-select>
                                        <span v-else>{{capaCity.year}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span='12'>
                                    <el-form-item label="课题负责人" prop="leadingmanName" :rules="rules">
                                        <PersonSelect
                                          v-if="edit"
                                          :value="capaCity.leadingmanName"
                                          v-bind:multiple="false"
                                          ref="leadingmanName">
                                        </PersonSelect>
                                        <span v-else>{{capaCity.leadingmanName}}</span>
                                    </el-form-item>
                                </el-col>
                              <el-col :span='12'>
                                <el-form-item label="课题成员组" prop="memberName" :rules="rules">
                                  <PersonSelect
                                    v-if="edit"
                                    :value="capaCity.memberName"
                                    v-bind:multiple="true"
                                    ref="memberName">
                                  </PersonSelect>
                                  <span v-else>{{capaCity.memberName}}</span>
                                </el-form-item>
                              </el-col>
                            </el-row>
                            <el-row>
                              <el-col :span="24">
                                    <el-form-item label="能力建设总体目标" prop="projectTarget" :rules="rules">
                                        <el-input
                                            v-if="edit"
                                            class="form-input"
                                            v-model="capaCity.projectTarget"
                                            type="textarea"
                                            :rows="4"
                                            size="small"
                                            placeholder="500个汉字以内"
                                            maxlength="500"
                                            show-word-limit>
                                        </el-input>
                                        <span v-else>{{capaCity.projectTarget}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                              <el-col :span="22">
                                <el-form-item label="年度计划及考核指标" prop="phases" :rules="rules">
                                  <div>
                                    <el-button
                                      v-if="edit"
                                      type="primary"
                                      size="small"
                                      @click="addPhasesHandle">
                                      新增
                                    </el-button>
                                  </div>
                                  <el-table
                                      class="table"
                                      border
                                      ref="phases"
                                      :data="phases"
                                      tooltip-effect="dark"
                                      style="width: 100%"
                                      :show-overflow-tooltip="true"
                                      :header-cell-style="{background:tableHeaderBGC}">
                                          <el-table-column type="index" :label="$t('cm.no')" align="center" width="60"></el-table-column>
                                          <el-table-column prop="phaseName" label="阶段" align="center"></el-table-column>
                                          <el-table-column prop="startTime" label="开始时间" :formatter="dateFormatstart" align="center"></el-table-column>
                                          <el-table-column prop="endTime" label="结束时间" :formatter="dateFormatend" align="center"></el-table-column>
                                          <el-table-column prop="jdMb" label="研究内容和考核指标" align="center"></el-table-column>
                                          <el-table-column v-if="edit" :label="$t('cm.operate')" prop="statussss" align="center" width="150">
                                            <template slot-scope="scope">
                                              <ListBtn
                                                :options="btns"
                                                :row-data="Object.assign({},scope.row,{index:scope.$index})"
                                                @triggerListBtn="phasesHandleListBtn">
                                              </ListBtn>
                                            </template>
                                          </el-table-column>
                                    </el-table>
                                </el-form-item>
                              </el-col>
                            </el-row>
                            <!-- v-if="edit"  <span v-else>{{capaCity.fileName}}</span>-->
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="附件"  prop="fileId">
                                       <FileUploadCommon

                                        @uploadSuccess="uploadSuccess"
                                        @uploadRemove="uploadRemove"
                                        :fileList="capaCityFileList"
                                        :limit="1">
                                       </FileUploadCommon>

                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                              <el-col :span="22" v-if="type === 'close' || capaCity.closeReason">
                                    <el-form-item label="关闭原因" prop="closeReason" :rules="rules">
                                        <el-input
                                            v-if="type === 'close'"
                                            v-model="capaCity.closeReason"
                                            type="textarea"
                                            :rows="4"
                                            size="small"
                                            placeholder="500个汉字以内"
                                            maxlength="500"
                                            show-word-limit>
                                        </el-input>
                                        <span v-else>{{capaCity.closeReason}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                        </div>

                    </el-collapse-item>
                </el-collapse>
                <!--流程部分-->
                <el-collapse v-model="showCollapse1" accordion v-if="type !='look'&&type !='done'">
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('fe.procDeal')}}</font>
                        </template>
                        <div>
                            <procApprove :isStartAct="isStartAct" :procObj="flowDetails" :flow_access="flow_access" ></procApprove>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                <!--流程部分 我的已办-->
                <el-collapse v-model="showCollapse1" accordion v-if="type =='done'">
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('fe.procDeal')}}</font>
                        </template>
                        <div>
                          <!--当前处理环节-->
                          <el-row class="flow-detail-row">
                            <el-col :span="4" class="flow-detail-col1" >{{$t('ndt.now_deal_actor')}} <span>&nbsp;</span></el-col>
                            <el-col :span="6" class="flow-detail-col2">{{flow_access.act_name}}</el-col>
                          </el-row>
                          <!--处理结论-->
                          <!--下一步处理环节-->
                          <el-row class="flow-detail-row">
                            <el-col :span="4" class="flow-detail-col1" >处理人</el-col>
                            <el-col :span="6" class="flow-detail-col2">
                              {{flow_access.approveMan}}
                            </el-col>
                          </el-row>
                          <!--下一步处理人-->
                          <!--抄送-->
                          <!--处理结论-->
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </el-form>
        </div>
        <el-row class="row-empty-30"></el-row>
        <!-- 固定按钮的位置 -->
        <!--使用组件的方式来进行-->
        <fixedbutton v-if="type !='look' && type !='done'">
            <div slot="fixbtn">
                <el-button class="btn-default" type="primary" size="small" @click="saveProcHandle" >{{$t('cm.commit')}}</el-button>
                <el-button v-if="type == 'add' || type == 'draftEdit'" class="btn-default" type="primary" size="small" @click="saveDraftHandle">{{$t('cm.savedraft')}}</el-button>
            </div>
        </fixedbutton>

    <!-- 项目阶段新增弹窗-->
    <el-dialog
      class="dialog"
      title="项目阶段"
      :visible.sync="phasesDialogVisible"
      width="50%">
      <el-form
        :model="phasesForm"
        label-position="right"
        label-width="150px"
        class="page-edit-colllapse-form"
        ref="phasesForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="阶段" prop="phaseName" :rules="rules">
              <span v-if="phasesDialogObj.type == 'look'">{{phasesForm.phaseName}}</span>
              <el-input
                  class="form-input"
                  v-else
                  v-model="phasesForm.phaseName"
                  size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间" prop="startTime" :rules="rules">
              <span v-if="phasesDialogObj.type == 'look'">{{phasesForm.startTime | dateFormatType}}</span>
              <el-date-picker
                v-else
                class="form-input"
                @change="changeStart(phasesForm.startTime)"
                :picker-options="pickerOptionsStart"
                v-model="phasesForm.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间" prop="endTime" :rules="rules">
              <span v-if="phasesDialogObj.type == 'look'">{{phasesForm.endTime | dateFormatType}}</span>
              <el-date-picker
                v-else
                class="form-input"
                @change="changeEnd(phasesForm.endTime)"
                :picker-options="pickerOptionsEnd"
                v-model="phasesForm.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="研究内容和考核指标" prop="jdMb"  :rules="rules">
              <span v-if="phasesDialogObj.type == 'look'">{{phasesForm.jdMb}}</span>
              <el-input class="form-input" v-else v-model="phasesForm.jdMb" type="textarea" :rows="4" size="small" placeholder="500个汉字以内" maxlength="500" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPhasesCancel">取 消</el-button>
        <el-button v-if="phasesDialogObj.type != 'look'" type="primary" @click="addPhasesConfirm">确 定</el-button>
      </span>
    </el-dialog>

    </div>
    </PageTemplate>
</template>

<script>
import PageTemplate from '@/components/common/PageTemplate'
import {
  getStartAct,
  insertwin,
  delFile,
  addDraft,
  getNextApprovePerson,
  getBpmPscActInfo,
  getWFConfigActivity,
  getWFConfigProcID
} from '@/api/api.js'
import PersonSelect from '@/components/asc/PersonSelect'
import procApprove from '@/components/common/procApprove'
import fixedbutton from '@/components/common/fixedbutton'
import download from '@/components/common/download'
import PurProcessDemWithinFileList from '@/components/purchase/PurProcessDemWithinFileList'
import { mapState, mapActions } from 'vuex'
import * as Constant from '@/utils/constant'
import { ALERT } from '@/utils/responseHandle'
import api_pur from '@/api/api_pur'
import store from '@/store'
import sys_manage from '@/api/sys_manage'
import api_sri from '@/api/api_sri'
import FileUploadCommon from '@/components/common/FileUploadCommon'
import ListBtn from '@/components/btn/ListBtn'
import {COMMON} from '@/utils/commonUtil'
import startEndDate from '@/mixins/startEndDate'


export default {
    components:{
      PageTemplate,
      PersonSelect,
      procApprove,
      fixedbutton,
      download,
      PurProcessDemWithinFileList,
      FileUploadCommon,
      ListBtn
    },
    mixins:[ startEndDate ],
    props: {
      // look：查看；edit：编辑; add: 新增; approve:审批; close:关闭
      type: {
        type: String,
        default: "look"
      },
    },
    data() {
        return {

            phasesDialogVisible:false,//新增项目阶段弹窗是否显示
            phasesForm:{},//新增项目阶段弹窗表单
            phasesDialogObj:{//项目阶段弹窗状态新增查看还是编辑
              index:null,//若为编辑时需存入编辑的下标
              type:"look"
            },
            phases:[],
            isStartAct: true, // 是否新建
            fileListDislogVisible: false, //
            fileUploadUrl:process.env.UPDOWN_ROOT,
            showCollapse2:"1",
            showCollapse:"1",
            hasIcon:false,
            loading:false,
            fileList:[],
            fileListDownLoad:[],
            showCollapse1:"1",
            flowDetails:{
                nextActOptions:[],
                approvePerson:[],
                approvePersonId:[],
                activityName:'010',
                isEnd:false,
                actParticipants:{}
            },
            fileProps:[ //文件上传的属性
                {prop:'fileRealName',label:'文件名'},
                {prop:'createTime',label:'上传时间'},
            ],
            flow_access:{
                task_type:'',//任务类型
                mergeTask:'0',//合并任务
                slotCount:'1',//任务处理规则
                resign:'',//会签类型
                reselMan:'',//是否重选快速审批人
                act_name:'',//当前节点名称
                now_deal_act:'010',//当前节点
                deal_answer:'1',//同意 还是退回
                next_deal_act:'',//下一节点
                next_deal_name:[],//下一处理人 [pxmwrya]阮洋  多个
                deal_suggest:'',//审批意见
                copygive:[],//抄送人
                approveMan:'',//当前提交人 自己
                procInstId:'',//流程实例ID
                sn:'',//sn
                backAct:'',//退回节点  020
                backMan:'',//退回人
                procSetId:'',//流程集ID 兑奖流程 463
                fullName:'BMWS\\TestProcess',//流程全名
                procChName:'',//流程中文名
                procVerId:'',
                isEnd:false,

            },
          capaCity:{
            // folio: '1',
            // fileId: 'aa',
            // deptId:'', //部门
            // deptName: '不知道什么部门',
            // contactUser:'',//联系人
            // mobile:'',//联系方式
            // year:'',//年度
            // purchaseContractItemList: [] //
            processName:"",
            // operateType:"1",
          },
          btns: [
              {
                value: 'look',
                label: 'cm.look'
              },
              {
                value: 'edit',
                label: 'cm.edit'
              },
              {
                value: 'del',
                label: 'cm.delete'
              }
            ],
          rules:[{ required: true, message: '必填项',trigger: 'change'}],
          nextThreeYear:[],//往后三年字典
          capaCityFileList:[],

          nextObj: {},
          WFConfigActivityList:[],//储存全部节点信息
          operationMap:{
            add:"计划新增",
            close:"计划关闭",
            edit:"计划变更",
            draftEdit:"修改草稿",
            approve:"计划审批"
          },

      }
     },
     computed: {
        ...mapState({
          tableHeaderBGC: state => state.common.tableHeaderBGC
        }),
        edit(){
          const { type } = this;
          return type == 'add' || type == 'edit' || type == 'draftEdit'
        }

    },
    watch: {


    },
    mounted() {

      //获取全部字典
      this.getAllMap();

      //数据初始化
      this.initData();


      //不是新增都需要显示详情
      if(this.type != "add" ){
        let id =""
        if(this.type == "approve"){
           id = this.$router.history.current.query.obj.formInstID
        }else if(this.type == "draftEdit"){
           id = this.$router.history.current.query.obj.formno
        }else if(this.type == "done"){
          id = this.$router.history.current.query.obj.fromNO
        }else{
           id = this.$router.history.current.params.id
        }

        //获取详情
        this.getDetail(id)

      }
      if(this.type == "approve"){
         this.isStartAct = false;
         this.nextObj = this.$router.history.current.query.obj || {};

         const {
           procInstID,
           showBack,
           backAct,
           backActName,
           backManName,
           backMan,
         } = this.nextObj;


        this.flowDetails = Object.assign({}, this.flowDetails, {
          showBack,
          backAct,
          backMan,
          backActName,
          backManName
        })
         this.flow_access = Object.assign({}, this.flow_access, {
          procInstId:procInstID,
          backAct,
          backMan,
          backManName,
        })
      }

      if(this.type == "draftEdit"){
         this.nextObj = this.$router.history.current.query.obj || {};
         const {
           sourceactmetadata,
           targetactmetadata,
           startuser,
           startusercn,
           id,
         } = this.nextObj
         if(sourceactmetadata === "010"){
           this.isStartAct =true;
         }else{
           this.isStartAct =false;
         }
        this.flow_access.next_deal_act = targetactmetadata;
        let name = `[${startuser}]${startusercn}`;
        this.flow_access.next_deal_name.push(name);
        this.$set(this.flow_access,"draftId",id);
        this.$set(this.flow_access,"next_deal_id",this.nextObj.startuser.split(","));
      }

      if(this.type == "done"){
        this.nextObj = this.$router.history.current.query.obj || {};
        this.flow_access.act_name = this.nextObj.actName;
        this.flow_access.approveMan = `[${this.nextObj.startUser}]${this.nextObj.startCNUser}`;
      }

    },
    methods: {
        dateFormatstart(thistime, fmt) {
          console.log("--552-cbp/plan/detail-",thistime);
          if (!COMMON.isNullOrUndefinedOrSpace(thistime.startTime)) {
                var date = new Date(thistime.startTime)
                var month =date.getMonth()+1;if(month<10){month="0"+month;}
                var day =date.getDate();if(day<10){day="0"+day;}
                var hours =date.getHours();if(hours<10){hours="0"+hours;}
                var min= date.getMinutes();if(min<10){ min="0"+min; }
                var sec= date.getSeconds();if(sec<10){sec="0"+sec;}
              return  date.getFullYear() + '-' + month + '-' + day
          }
              return thistime.startTime
        },
        dateFormatend(thistime, fmt) {
              console.log("--565-cbp/plan/detail-",thistime);
                  if (!COMMON.isNullOrUndefinedOrSpace(thistime.endTime)) {
                        var date = new Date(thistime.endTime)
                        var month =date.getMonth()+1;if(month<10){month="0"+month;}
                        var day =date.getDate();if(day<10){day="0"+day;}
                        var hours =date.getHours();if(hours<10){hours="0"+hours;}
                        var min= date.getMinutes();if(min<10){ min="0"+min; }
                        var sec= date.getSeconds();if(sec<10){sec="0"+sec;}
                      return  date.getFullYear() + '-' + month + '-' + day
                  }
                      return thistime.endTime
                },

        //获取全部字典
        getAllMap(){
           //获取往后3年年份
          api_sri.sriGainGetNextThreeYear({}, result => {
            if (result.code === Constant.RT_SUCCESS) {
              this.nextThreeYear = result.years
            } else {
              ALERT.error(result.msg)
            }
          })

        },

       uploadSuccess (res, fileKey) {
          if (res.data && res.data[0]) {
            this.capaCity.fileId = res.data[0].fileId
            let file = {name: res.data[0].fileName, url: res.data[0].url, id: res.data[0].fileId}
            this.capaCityFileList.push(file)
          }
        },
        uploadRemove (fileList, fileKey) {
          let resList = fileList.map(item => {
            return {
              name: item.name,
              url: item.url,
             id: item.fileId
            }
          })
          this.capaCityFileList = resList
          this.capaCity.fileId = resList.map(item=>item.id).join(",");
        },

        //阶段新增
        addPhasesHandle(){
          this.phasesDialogVisible = true;
          this.phasesDialogObj = {
            type:"add",
            index:null
          }
        },
        //弹窗确认
        addPhasesConfirm(){
          this.$refs.phasesForm.validate((valid, error) => {
            if (valid) {
              if(this.phasesDialogObj.type =="add"){//新增
                if(!this.phases) this.phases = [];
                this.phases.push(this.phasesForm)
              }else if(this.phasesDialogObj.type =="edit"){//编辑
                this.phases[this.phasesDialogObj.index] = this.phasesForm
                 console.log("---20210818--row:602---:"+this.phasesForm);
                               console.log(this.phasesForm);
              }
              this.phasesDialogVisible = false;
              this.phasesForm = {}

            }
          })
        },
        //弹窗取消
        addPhasesCancel(){
          this.phasesDialogVisible = false;
          this.phasesForm = {}
        },
        //列表操作按钮点击
        phasesHandleListBtn({btn,row}){
          if(btn==="look"){//查看
            this.phasesDialogVisible = true;
            this.phasesDialogObj = {
              type:"look",
              index:null
            };
            this.phasesForm = row
          }else if(btn==="edit"){//编辑
            this.phasesDialogVisible = true;
            this.phasesDialogObj = {
              type:"edit",
              index:row.index
            };
            this.phasesForm = this.phases[row.index]
          }else if(btn==="del"){//删除
              COMMON.confirm({}, () => {
                this.phases.splice(row.index,1)
              })
          }
        },

        //获取详情
         getDetail(id){
          api_sri.sriGainCapacityBuildingPlanInfo({id}, result => {
            if (result.code === Constant.RT_SUCCESS) {
               this.capaCity = result.data.capacityBuildingInfo
               this.phases = result.data.capacityPlanPhaseList
               //console.log("---20210818--row:645---:"+this.phases);
              //已有附件
              if(this.capaCity.fileId){
                this.capaCityFileList =[
                    {
                      name:this.capaCity.fileName,
                      id:this.capaCity.fileId,
                      url:this.capaCity.filePath
                    }
                  ]
              }
              this.$nextTick(()=>{
                  this.$refs.capaCity.clearValidate();
              })
            } else {
              ALERT.error(result.msg)
            }

          })

        },
        //数据初始化
        initData:function(){
            this.flow_access.procChName = store.state.proc.procName ? store.state.proc.procName : '能力建设年度计划审批';
            this.flow_access.fullName = 'SWP-SU\\sci_cbpPlan';
            this.flow_access.procSetId = store.state.proc.procSetId;
            this.flow_access.procVerId = store.state.proc.procId;
            this.capaCity.processName = this.flow_access.procChName;
            //获取最新流程procId
            this.getWFConfigProc({fullName: this.flow_access.fullName});
        },
        getWFConfigProc(params){ // 获取最新流程procId
          let _this = this;
          getWFConfigProcID(params).then((result) => {
            if(result.status == "200" && result.data.code == "0"){
               let data = result.data.data || {}
               _this.flow_access.procSetId  = data.procSetID
              //  审批需要
               _this.flow_access.procId  = data.procID

              _this.getSomeInfo(data.procID);
            }else{
                _this.$alert(result.data.msg,_this.$t('cm.tips'));
            }
          }).catch((err) => {
              _this.$alert(err,_this.$t('cm.tips'));
          });
        },

        getSomeInfo(procVerId){

        },
        getSomeInfo(procVerId){
          let _this = this;
            //获取全部节点信息
           this.getWFConfigActivityHandle((result)=>{
                //储存全部节点信息
                _this.WFConfigActivityList = result.data.data.data;
                if(this.type=='approve'){
                    //获取流程的开始节点、下一节点还有下一节点处理人
                    let act_metadata_cur = null;
                    //匹配当前节点
                    let d = _this.WFConfigActivityList;//result.data.data.data;
                    for (let i = 0; i < d.length; i++) {
                        if (d[i].actName == _this.nextObj.activityName) {
                            act_metadata_cur = d[i].actMetaData
                        }
                    }
                  // if(this.nextObj.activityName == "010_提交能力建设年度工作计划"){
                  //     act_metadata_cur = "010";
                  // }else if(this.nextObj.activityName == "020_专业分部协调员审批") {
                  //     act_metadata_cur = "020";
                  // }else if(this.nextObj.activityName == "030_能力建设管理工程师审批"){
                  //     act_metadata_cur = "030";
                  // } else if(this.nextObj.activityName =="040_主任或副主任审批"){
                  //     act_metadata_cur = "040";
                  // }


                  let data = {
                    act_id: this.nextObj.activityID,
                  //   act_metadata: this.nextObj.backAct[0], //这里不能这样判断，backAct不可能是当前环节的act_metadata
                    act_metadata: act_metadata_cur,
                    act_name: this.nextObj.activityName,
                    proc_id: this.nextObj.procID
                  }
                  _this.flow_access.act_name = data.act_name;//当前环节名称
                  _this.flowDetails.activityName = data.act_name;//用于页面显示
                  _this.flow_access.staffNoBefore=this.nextObj.preActivitySender; //上一审批人
                  _this.flow_access.procId = this.nextObj.procID;//提交需要
                  _this.flow_access.actId = this.nextObj.activityID;//提交需要
                  _this.flow_access.now_deal_act  = act_metadata_cur
                  //获取下一处理环节
                  _this.getNextDealNode(data);
              }else{
                  //获取流程的开始节点、下一节点还有下一节点处理人
                  let _this = this;
                  getStartAct(procVerId).then((result) => {
                      if(result.status == "200" && result.data.code == "0"){
                          let data = result.data.data.data;
                          _this.flow_access.act_name = data.act_name;//当前环节名称
                          _this.flowDetails.activityName = data.act_name;//用于页面显示
                          //获取下一处理环节
                          _this.getNextDealNode(data);
                      }else{
                          _this.$alert(result.data.msg,_this.$t('cm.tips'));
                      }
                  }).catch((err) => {
                      _this.$alert(err,_this.$t('cm.tips'));
                  });

              }
           })

        },
         configFormData() {
           if(this.type != "close"){
              this.$set(this.capaCity, "leadingmanName", COMMON.changePersonSelectData(this.$refs.leadingmanName, false).peopleName)
              this.$set(this.capaCity, "leadingman", COMMON.changePersonSelectData(this.$refs.leadingmanName, false).peopleNumber)
            }
            //处理阶段信息 验证rule
            let phases = this.phases.length ?  this.phases : "";
             this.$set(this.capaCity,"phases",phases)
        },
        // 保存草稿防抖
        saveDraftHandle:COMMON.debounce('saveProc',500,true),

       // 提交流程防抖
        saveProcHandle:COMMON.debounce('saveProc'),

        // 提交流程
        saveProc(isSaveDraft = false) {
            if(isSaveDraft || this.isStartAct){
               this.addProc(isSaveDraft);
            }else {
                this.purSubmitProcess();
            }
        },
        //添加一个流程
        addProc:function(isSaveDraft){
            this.configFormData();
            //下一步处理人 设置
            if(document.getElementById("appMan")!= null && document.getElementById("appMan").value != ""){
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');
            }

            //判断是否为保存草稿
            if(isSaveDraft){
                this.flow_access.isSaveDraft = "1"; //说明是保存草稿
                this.flow_access.isModifyDraft = this.type === "draftEdit" ? "1" :"0" //编辑草稿
            }else {
                 this.flow_access.isSaveDraft = "0";
            }

            //判断获奖表
            this.$refs['capaCity'].validate((valid)=>{
                if(valid){
                    if (this.checkValid()) {
                        //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
                        let selNextAct = this.flowDetails.nextActOptions.find(n =>{
                            return (n.actMetadata == this.flow_access.next_deal_act);
                        })

                        this.flow_access.task_type = selNextAct.taskActType;
                        this.flow_access.mergeTask = selNextAct.isMergeTask;
                        this.flow_access.slotCount = selNextAct.taskProcessRule;
                        this.flow_access.resign = selNextAct.reSignType;
                        this.flow_access.reselMan = selNextAct.isReselFastDealer;

                        //设置关联文件
                        this.flow_access.fileList = this.fileListDownLoad;

                        // operateType 参数
                        if(this.type == "add"){
                          this.capaCity.operateType = "1"
                        }else if(this.type == "edit"){
                          this.capaCity.operateType = "2"
                        } else{
                          this.capaCity.operateType = "3"
                        }

                        let _this = this;
                        this.flow_access.capaCity = this.capaCity;
                        this.flow_access.phases = this.phases;
                        delete this.capaCity.phases;

                        api_sri.sriGainCapacityBuildingPlanSave(this.flow_access, result => {
                          if (result.code === Constant.RT_SUCCESS) {
                            ALERT.success(result.msg)
                            if(isSaveDraft){
                                _this.$router.push(Constant.ROUTE_MYDRAFT.index);
                            }else{
                                _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
                            }
                          } else {
                            ALERT.success(result.msg)
                          }
                        })
                    }
                }else{
                    return false;
                }
            })
        },
        getNextDealNode:function(data){//获取下一节点 通过 下一步点处理人接口
            let _this = this;
            let procInstId = this.type=='approve' ? _this.nextObj.procInstID :0;
            let params = {
                actId: data.act_id,
                procInstId,
                procId: data.proc_id,
                node: data.act_metadata,
            }
            getNextApprovePerson(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    this.getNextNodeInfo(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        //获取全部节点信息
        getWFConfigActivityHandle(calback){
            let _this = this;
            let params = {
                fullName: this.flow_access.fullName,
                procSetId: "", //this.flow_access.procSetId
            };
            getWFConfigActivity(params).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    calback(result)
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });

        },
        //获取下一节点详情
        getNextNodeInfo: function (data) {
            //获取流程配置中的流程节点信息  可以存储在store中getBpmPscActInfo
            let _this = this;
            //存在多个下一环节的情况
            console.log('存在多个下一环节的情况', data)
            for (const metadata in data) {
                let d = _this.WFConfigActivityList;//result.data.data.data;
                for (let i = 0; i < d.length; i++) {
                    if (d[i].actMetaData == metadata) {
                        _this.flowDetails.actParticipants[metadata] = data[metadata];
                        _this.getNextNodeDetails(d[i]);
                    }
                }
            }
        },

        // 审批流程
        purSubmitProcess () {
          //抄送人
          if(document.getElementById("sendToMan")!= null && document.getElementById("sendToMan").value != ""){
              this.flow_access.copygive = document.getElementById("sendToMan").value.split(',');
          }
          //下一步处理人
          if(this.flow_access.participantSelectRestlt) {
              let value = [];
              let parts = this.flow_access.participantSelectRestlt.split(",");
              for(let i = 0; i < parts.length; i++){
                  value.push(parts[i]);
              }
              this.flow_access.next_deal_name = value;
          }
          if(this.checkValid()){
              //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
              let selNextAct = this.flowDetails.nextActOptions.find(n =>{
                  // return (n.actMetadata == this.flow_access.next_deal_act);
                  return true
              })

              // this.flow_access.act_name = selNextAct.actName;//当前环节名称
              // this.flow_access.actId = selNextAct.actId;//当前环节Id
              this.flow_access.act_name = this.nextObj.activityName;//当前环节名称
              this.flow_access.actId = this.nextObj.activityID;//当前环节Id
              this.flow_access.task_type = selNextAct.taskActType;
              this.flow_access.mergeTask = selNextAct.isMergeTask;
              this.flow_access.slotCount = selNextAct.taskProcessRule;
              this.flow_access.resign = selNextAct.reSignType;
              this.flow_access.reselMan = selNextAct.isReselFastDealer;
              this.flow_access.auditNote = this.flow_access.deal_suggest;
              this.flow_access.formInstID = this.nextObj.formInstID;
              this.flow_access.procInstId = this.nextObj.procInstID;
              this.flow_access.sn = this.nextObj.sn;

              //处理回退逻辑
              this.flow_access.backAct = this.nextObj.backAct[0];
              this.flow_access.backMan = this.nextObj.backMan[0];
              this.flow_access.backManName = this.nextObj.backManName[0];

              //设置关联文件
              this.flow_access.fileList = this.fileListDownLoad;
              let _this = this;
              api_sri.sriGainCapacityBuildingPlanSubmitProcess(this.flow_access, result => {
                if (result.code === Constant.RT_SUCCESS) {
                  ALERT.success(result.msg)
                  _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
                } else {
                  ALERT.success(result.msg)
                }
              })
          }
        },
        //获取下一节点详细信息
        getNextNodeDetails(arr){
            let _this = this;
            getBpmPscActInfo({actId:arr.actID}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    //获取下一步点处理人
                    console.log('获取下一步点处理人', data)
                    _this.flowDetails.nextActOptions.push(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });

        },
        //统一用户格式
        unifyUser:function(users){
            for(let i = 0; i < users.length; i++){
                if(typeof(users[i].item_principal_desc) != "undefined" && typeof(users[i].item_principal_desc) != null){
                    this.flowDetails.approvePerson.push("["+users[i].item_principal+"]"+users[i].item_principal_desc);
                    this.flowDetails.approvePersonId.push(users[i].item_principal);
                }
            }
        },
        //上传文件时的回调
        upfileBack:function(response, file, fileList){
            this.loading = false;
            if(response.code == "0"){
                this.fileListDownLoad.push(response.data);
            }else{
                this.$alert(response.msg,this.$t('cm.tips'));
            }
        },
        //上传文件之前的处理
        beforeUpload:function(file){
            //在这里进行上传文件的设置
            let type = file.name.substring(file.name.lastIndexOf('.')+1);
            const limitSize = file.size / 1024 /1024 < 10; //文件大小限制
            if(!limitSize){
                this.$alert("上传文件大小不能超过10M",this.$t('cm.tips'));
            }
            return limitSize;
        },
        loadingFile:function(){
            this.loading = true;
        },
        uplofileError:function(){
            this.loading = false;
        },
        //删除文件
        delFiles:function(row){
            let _this = this;
            delFile({fileId:row.fileId}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    _this.fileListDownLoad.splice(_this.fileListDownLoad.findIndex(item => item.fileId===row.fileId),1);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        checkValid() {
            if (!this.flow_access.deal_answer) {
                this.$alert("请选择处理结论!", this.$t('cm.tips'));
                return false;
            } else if (!this.flow_access.next_deal_act) {
                this.$alert("请选择下一环节!", this.$t('cm.tips'));
                return false;
            } else if (!this.flow_access.isEnd&&this.flow_access.deal_answer==1&&this.flow_access.next_deal_name.length == 0) {
                this.$alert("请选择下一步处理人", this.$t('cm.tips'));
                return false;
            } else {
                return true;
            }
        },
        addFileListDislog () {
          this.fileListDislogVisible = true
        },
        closeFileListDislog () {
          this.fileListDislogVisible = false
        },
        addFileList (data) {
          this.capaCity.purchaseContractItemList = data
          this.fileListDislogVisible = false
        }
    },
    filters:{
           dateFormatType(data) {
              console.log("timedata--1065--"+data);
              if (!COMMON.isNullOrUndefinedOrSpace(data)) {
                    var date = new Date(data)
                    var month =date.getMonth()+1;if(month<10){month="0"+month;}
                    var day =date.getDate();if(day<10){day="0"+day;}
                    var hours =date.getHours();if(hours<10){hours="0"+hours;}
                    var min= date.getMinutes();if(min<10){ min="0"+min; }
                    var sec= date.getSeconds();if(sec<10){sec="0"+sec;}

                  return  date.getFullYear() + '-' + month + '-' + day
              }
                  return data
            }

        }
}
</script>

<style lang="scss">
    .cbp-plan-detail{
      .el-table__header,
      .el-table__body,
      .el-table__footer{
          width: 100% !important;
      }
      .el-form-item__content>span:empty:before{
        content:"--"
      }
    }

</style>
